//
//  MyFlutterView.m
//  Runner
//
//  Created by mac on 2021/6/1.
//

#import "MyFlutterView.h"
@interface MyFlutterView()
@property (nonatomic, strong) UILabel *label;
@end

@implementation MyFlutterView
-(instancetype) initWithFrame:(CGRect) frame viewID:(SInt64)viewID args:(NSDictionary *)args messenger:(NSObject<FlutterBinaryMessenger> *)messenger{
    self = [super init];
    self.label = [[UILabel alloc] init];
    //从flutter获取数据
    self.label.text = args[@"text"];
    [self.label sizeToFit];
    
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"com.flutter.guide.MyFlutterView" binaryMessenger:messenger];
    
    __weak MyFlutterView *weakSelf = self;
    [channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        if ([call.method isEqual:@"setText"]) {
            NSString *info = [NSString stringWithFormat:@"hello %@,年龄：%d",call.arguments[@"name"],[call.arguments[@"age"] intValue]];
            weakSelf.label.text = info;
            [weakSelf.label sizeToFit];
            result(@{});
        } else if ([call.method isEqualToString:@"getData"]) {
            //可以延时返回
            [NSTimer scheduledTimerWithTimeInterval:2 repeats:NO block:^(NSTimer * _Nonnull timer) {
                result(@{@"name":@"张三",@"age":@(20)});
            }];
        } else if ([call.method isEqualToString:@"callNative"]) {
            NSDictionary *dic = call.arguments;
            NSString *action = dic[@"action"];
            //flutter传递给OC的数据
            NSDictionary *dataDic = dic[@"data"];
            NSLog(@"%@",dataDic);
            if ([action isEqualToString:@"closeFlutter"]) {
            }
            result(@{@"msg":@"原生返回Flutter"});
        } else {
            result(@{});
        }
    }];
    return self;
}

//这个就是返回给flutter渲染的原生view
- (UIView *)view{
    return self.label;
}
@end
